﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Remoting;
using System.Collections.ObjectModel;

/// <summary>
/// This class is the interface to Powershell for
/// - Operations within Active Directory (not in use within this SPA)
/// - Set NTFS permissions on a folder (Home Drive)
/// - other operations with powershell (not in use within this SPA)
/// </summary>
public class PSvarOps
{
	
    private string psCmd;
    private ADobjInfo adobjin;

    public string PSCmd
    { 
        get
        {
            return psCmd;
        }
        set
        {
            psCmd = value;
        }
    }        

    public ADobjInfo Adobjin
    {
        get
        {
            return adobjin;
        }
        set
        {
            adobjin = value;
        }
    }
    
    public List<string> RunPSCmd(out int retval, out string objContentMsg, ADobjInfo adobjin, string target = "various" )
    {
        
        retval = 0;
        List<string> rtnLst = new List<string>();                       
        
        Runspace runspace = RunspaceFactory.CreateRunspace();        
        PowerShell powershell = PowerShell.Create();
        PSCommand command = new PSCommand();
        powershell.Commands = command;
        
        try
        {                     
            
            switch(target)
            {
                case "activedirectory":
                    runspace.Open();
                    powershell.Runspace = runspace;
                    powershell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddScript("Import-Module ActiveDirectory");
                    powershell.Commands = command;
                    powershell.Runspace = runspace;
                    powershell.Invoke();

                    powershell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddScript(psCmd);
                    powershell.Commands = command;
                    powershell.Runspace = runspace;
                    break;

                case "fileserver":               
                    string directorie = adobjin.ADHomeDirve;
                    string sied = adobjin.ADSID;
    
                    runspace.Open();
                    runspace.SessionStateProxy.SetVariable("directorie", directorie);
                    runspace.SessionStateProxy.SetVariable("sID", sied);
                    powershell.Runspace = runspace;
                    powershell = PowerShell.Create();
                    command = new PSCommand();                 
                                                                          
                    string psString = @"$objSID = New-Object System.Security.Principal.SecurityIdentifier(""$sID"") 
                    $inherit = [system.security.accesscontrol.InheritanceFlags]""ContainerInherit, ObjectInherit""
                    $propagation = [system.security.accesscontrol.PropagationFlags]""None""	
                    $aCL = Get-Acl $directorie
                    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($objSID, ""Modify"", $inherit, $propagation, ""Allow"")    
                    $aCL.AddAccessRule($accessrule) 
                    Set-Acl -aclobject $aCL -path $directorie ";

                    command.AddScript(psString);
                    powershell.Commands = command;
                    powershell.Runspace = runspace;                   
                    break;

                case "various":
                    powershell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddScript(psCmd);
                    powershell.Commands = command;
                    powershell.Runspace = runspace;                
                    break;
            }          
                        
            var result = powershell.Invoke<PSObject>();                             
                 
            if (powershell.Streams.Error.Count > 0)
            {            
                foreach (ErrorRecord current in powershell.Streams.Error)
                {
                    rtnLst.Add("Exception: " + current.Exception.Message.ToString());
                    rtnLst.Add("Stack Trace: " + current.Exception.StackTrace.ToString());                    
                }
                powershell.Streams.Error.Clear();
                objContentMsg = "Problem record occured. ";
                retval = 1;
            }           
            else
            {
                string tmp = "";
                foreach (var item in result)                
                    tmp += item;

                rtnLst.Add(tmp);                    
                retval = 0;
                objContentMsg = "No error detected. ";
            }          
        }
            
        catch (System.Exception ex)        
        {        
            rtnLst.Add(ex.Message);
            rtnLst.Add(ex.StackTrace);
            objContentMsg = "Problem occured. " + ex.StackTrace;
            retval = 1;        
        }

        finally
        {            
            runspace.Dispose();
            runspace = null;            
            powershell.Dispose();
            powershell = null;
        }
        
        return rtnLst;

    }

}